'use strict';

import React from 'react';
import {
    AppRegistry,
    StyleSheet,
    Image,
    Modal,
    TextInput,
    Platform,
    ToastAndroid,
    Alert,
    TouchableHighlight,
    TouchableWithoutFeedback,
    Text,
    View
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import Dimensions from 'Dimensions';

const defaultWidth=Dimensions.get('window').width;
const defaultHeight=Dimensions.get('window').height;

const options = {
    title:'选择图片',
    cancelButtonTitle:'取消',
    takePhotoButtonTitle:'拍照',
    chooseFromLibraryButtonTitle:'选择相册',
    quality:0.75,
    allowsEditing:true,
    noData:false,
    storageOptions: {
        skipBackup: true,
        path:'images'
    }
};

export default class ImageUpload extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            avatarSource: [],
            imageFileName:[],
            imageName:"",
            textDescription:"",
            imageStatus:false,
        };
    }

    _imagePicker() {
        ImagePicker.showImagePicker(options,(res) => {
            if (res.didCancel) {  // 返回
                return
            } else {
                let source;  // 保存选中的图片
                source = {uri: 'data:image/jpeg;base64,' + res.data};
                if (Platform.OS === 'android') {
                    source = { uri: res.uri };
                } else {
                    source = { uri: res.uri.replace('file://','') };
                }
                let imageArray = this.state.avatarSource;
                imageArray.push(source);
                let imgFileNameArray= this.state.imageFileName;
                if(res.fileName != null){
                    imgFileNameArray.push(res.fileName);
                }
                this.setState({
                    avatarSource:imageArray,
                    imageFileName:imgFileNameArray,
                });
            }
        });
    }
    preView(imagePath){
        if(this.state.imageStatus == false){
            this.setState({
                imageName:imagePath,
                imageStatus:true,
            });
        }else{
            this.setState({
                imageStatus:false,
            });
        }
    }
    deleteImage(imageName){
        let path=this.state.avatarSource;
        for(var i=0;i<path.length;i++){
            if(imageName == path[i]){
                path[i] = null;
            }
        }
        this.setState({
            imageStatus:false,
            avatarSource:path,
        });
    }
    render(){
         let path=this.state.avatarSource;
         let imageName=this.state.imageName;
         let imageStatus=this.state.imageStatus;
         let list=[];
         for(var i=0;i<path.length;i++){
             let row=(
                 <TouchableWithoutFeedback key={i} onPress={this.preView.bind(this,path[i])}>
                    <Image style={styles.preUploadImage} source={path[i]} />
                 </TouchableWithoutFeedback>
             );
             list.push(row);
         }

        return (
            <View>
              <TextInput
                  multiline={true}
                  numberOfLines={1}
                  onChangeText={(textDescription) => this.setState({textDescription})}
                  value={this.state.textDescription}
                  placeholder='请输入评估描述'
              />
              <TouchableHighlight style={styles.plusStyle} onPress={this._imagePicker.bind(this)} underlayColor='#2196F3'>
                  <Image style={styles.addImagePlus} source={require('../app/src/main/res/drawable/plus_white.png')}/>
              </TouchableHighlight>
              <View style={{flexDirection:'row'}}>
                {list}
              </View>
              <Modal visible={this.state.imageStatus}
                    transparent={true}
                    animationType = {'slide'}
                    onRequestClose={() => this.preView.bind(this,imageName)}
                    >
                    <View style={styles.flex}>
                          <Image style={styles.preImage} source={imageName}>
                                <CustomButton onPress={()=>Alert.alert('温馨提醒','是否删除该照片?',[
                                       {text:'取消',onPress:()=>this.preView(imageName)},
                                       {text:'确定',onPress:()=>this.deleteImage(imageName)}
                                       ])}
                                />
                          </Image>
                    </View>
              </Modal>
            </View>
        );
    }
}

class CustomButton extends React.Component {
    constructor(props){
        super(props);
    }
    render(){
        return(
            <TouchableHighlight
                style={styles.delImage}
                underlayColor='rgba(52,52,52,0.5)'
                onPress={this.props.onPress}>
                <Image source={require('../app/src/main/res/drawable/delete_white.png')} />
            </TouchableHighlight>
        );
    }
}

const styles = StyleSheet.create({
    flex:{
        width: defaultWidth,
        height: defaultHeight,
        backgroundColor: 'rgba(52,52,52,0.5)',
        justifyContent: 'center',
        alignItems: 'center',
    },
     plusStyle:{
         width:40,
         height:40,
         borderWidth:0.5,
         borderColor:'#2196F3',
         backgroundColor:'#2196F3',
         borderRadius:8,
     },
     addImagePlus:{
         width:22,
         height:22,
         marginTop:8,
         marginLeft:8,
     },
     preUploadImage:{
         width:defaultWidth * 0.25,
         height:defaultHeight * 0.2,
         marginTop:10,
         marginBottom:10,
         marginRight:5,
     },
     preImage:{
         width:defaultWidth * 0.85,
         height:defaultHeight * 0.58,
     },
     delImage:{
         width:14,
         height:14,
         alignSelf:'flex-end',
     },
 });
